package com.wjq.controller;

import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wjq.entity.*;
import com.wjq.service.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.javassist.NotFoundException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
public class QuestionnaireController {

    @Autowired
    QuestionnaireService questionnaireService;

    @Autowired
    ChoiceQuestionService choiceQuestionService;

    @Autowired
    ChoiceService choiceService;

    @Autowired
    EssayQuestionService essayQuestionService;

    @Autowired
    ResultServiceImpl resultService;

    @GetMapping("/questionnaire/{id}")
    public String selectAllInfoQuestionnaireById(@PathVariable("id") Integer id) throws JsonProcessingException, NotFoundException {
        Questionnaire questionnaire = questionnaireService.selectAllInfoById(id);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(questionnaire);
        return s;
    }

    @RequestMapping("/deleteQuestionnaire")
    public String deleteQuestionnaire(@RequestParam("id") Integer id) {//requestparam前端传的数据
        System.out.println(id);
        questionnaireService.deleteQuestionnaire(id);
        //调用service修改方法
        return "SUCCESS";
    }

    @RequestMapping("/recoverQuestionnaire")
    public String recoverQuestionnaire(@RequestParam("id") Integer id) {//requestparam前端传的数据
        System.out.println(id);
        questionnaireService.recoverQuestionnaire(id);
        //调用service修改方法
        return "SUCCESS";
    }

    @RequestMapping("/publicQuestionnaire")
    public String qublicQuestionnaire(@RequestParam("id") Integer id) {//requestparam前端传的数据
        System.out.println(id);
        questionnaireService.publicQuestionnaire(id);
        //调用service修改方法
        return "SUCCESS";
    }

    @RequestMapping("/unPublicQuestionnaire")
    public String unPublicQuestionnaire(@RequestParam("id") Integer id) {//requestparam前端传的数据
        System.out.println(id);
        questionnaireService.unPublicQuestionnaire(id);
        //调用service修改方法
        return "SUCCESS";
    }

    @RequestMapping("saveQuestion")
    public String saveQuestion(String questions, HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        String decode = URLDecoder.decode(questions, "utf-8");
//        System.out.println("decode" + decode);
//        System.out.println();
/*        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList arrayList = objectMapper.readValue(decode, ArrayList.class);
        for (int i = 0; i < arrayList.size(); i++) {
            JSONObject arrayListi = JSONObject.fromObject(arrayList.get(i));
            JSONObject jsonObject = JSONObject.fromObject(arrayListi);
            JSONArray optionsArray = jsonObject.getJSONArray("options");
            List<String> options = new ArrayList<>();
            for (int j = 0; j < optionsArray.size(); j++) {
                JSONObject object = (JSONObject) optionsArray.get(j);
                String option = (String) JSONObject.toBean(object, String.class);
                options.add(option);
            }
            System.out.println("options");
            options.forEach(System.out::println);
        }*/


//        System.out.println();
//        System.out.println("decode" + decode);
        return "SUCCESS";
    }

    @RequestMapping("saveQuestionnaire")
    public String saveQuestionnaire(String quDate, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        String decode = URLDecoder.decode(quDate, "utf-8");

//        System.out.println("quDate" + decode);

        JSONObject jsonObject = JSONObject.fromObject(decode);
        JSONArray questionsArray = jsonObject.getJSONArray("questions");
        String questionnaireName = jsonObject.getString("name");
        String questionnaireCreateTime = jsonObject.getString("createTime");
        int questionnairePublishId = jsonObject.getInt("publishId");
        int questionnairePublishState = jsonObject.getInt("state");
        Choice choice = new Choice();
        ChoiceQuestion choiceQuestion1 = new ChoiceQuestion();

        //插入问卷
        Questionnaire questionnaire = new Questionnaire();
        questionnaire.setName(questionnaireName);
        questionnaire.setCreateTime(questionnaireCreateTime);
        questionnaire.setPublishState(questionnairePublishState);
        questionnaire.setPublishState(0);
        questionnaire.setFillState(0);
        questionnaire.setPublishId(questionnairePublishId);
        questionnaire.setIsDelete(0);
        questionnaireService.addQuestionnaire(questionnaire);

//        questionsArray.forEach(System.out::println);

        //插入所有问题
        for (int i = 0; i < questionsArray.size(); i++) {
            JSONObject question = JSONObject.fromObject(questionsArray.get(i));
            System.out.println(question);
            String type = question.getString("type");
            String description = question.getString("description");
            int isMandatory = question.getInt("isMandatory");

            if (type.compareTo("radio") == 0 || type.compareTo("checkbox") == 0) {
                question.getInt("multiSelect");
                JSONArray optionsArray = question.getJSONArray("options");
                ChoiceQuestion choiceQuestion = JSON.parseObject(question.toString(),ChoiceQuestion.class);

                //插入选择题
                choiceQuestion.setQuestionnaireId(questionnaire.getId());
                choiceQuestion.setIsMandatory(1);
                choiceQuestion.setSerialNum(i + 1);
                //System.out.println(choiceQuestion);
                choiceQuestionService.addQuestion(choiceQuestion);
                Integer id = choiceQuestion.getId();
//                System.out.println(id);
                for(int j=0 ;j<optionsArray.size(); j++){
//                    System.out.println(optionsArray.get(j));
                    choice.setQuestionId(id);
                    choice.setDescription(optionsArray.get(j).toString());
                    char ch = (char) ('A'+j);
                    choice.setSerial(ch);
                    choiceService.addChoice(choice);
                }

            }else{
                //插入非选择题
                EssayQuestion essayQuestion = JSON.parseObject(question.toString(),EssayQuestion.class);
                essayQuestion.setQuestionnaireId(questionnaire.getId());
                essayQuestion.setDescription(description);
                essayQuestion.setIsMandatory(isMandatory);
                essayQuestion.setSerialNum(i+1);
                //System.out.println(essayQuestion);
                essayQuestionService.addQuestion(essayQuestion);
            }
        }
        return "SUCCESS";
    }

    @RequestMapping("updateQuestionnaire")
    public String updateQuestionnaire(String quDate, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        String decode = URLDecoder.decode(quDate, "utf-8");

//        System.out.println("quDate" + decode);

        JSONObject jsonObject = JSONObject.fromObject(decode);
        JSONArray questionsArray = jsonObject.getJSONArray("questions");
        int questionnaireId = jsonObject.getInt("id");
        String questionnaireName = jsonObject.getString("name");
        String questionnaireCreateTime = jsonObject.getString("createTime");
        int questionnairePublishState = jsonObject.getInt("publishState");
        int questionnairePublishId = jsonObject.getInt("publishId");
        int fillState = jsonObject.getInt("fillState");
        int isDelete = jsonObject.getInt("isDelete");
        Choice choice = new Choice();
        ChoiceQuestion choiceQuestion1 = new ChoiceQuestion();

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //更新问卷信息
        Questionnaire questionnaire = new Questionnaire();
        questionnaire.setId(questionnaireId);
        questionnaire.setName(questionnaireName);
        questionnaire.setCreateTime(questionnaireCreateTime);
        questionnaire.setModifyTime(sdf.format(date));
        questionnaire.setPublishId(questionnairePublishId);
        questionnaire.setPublishState(questionnairePublishState);
        questionnaire.setFillState(fillState);
        questionnaire.setIsDelete(isDelete);
        questionnaireService.updateQuestionnaire(questionnaire);


        //删除
        List<ChoiceQuestion> choiceQuestionList = choiceQuestionService.getQuestions(questionnaire.getId());
        List<EssayQuestion> essayQuestionList = essayQuestionService.getQuestions(questionnaire.getId());
//        System.out.println(choiceQuestionList);
        //System.out.println(essayQuestionList);
        for(int j=0 ; j<choiceQuestionList.size(); j++) {
            int id = choiceQuestionList.get(j).getId();
            choiceQuestionService.deleteQuestopn(id);
            List<Choice> choiceList = choiceService.getChoices(id);
            for(int k=0 ; k < choiceList.size(); k++){
                choiceService.deleteChoice(choiceList.get(k).getId());
            }
        }
        for(int j=0 ;j<essayQuestionList.size(); j++)
            essayQuestionService.deleteQuestion(essayQuestionList.get(j).getId());

        //新增
        for (int i = 0; i < questionsArray.size(); i++) {
            JSONObject question = JSONObject.fromObject(questionsArray.get(i));
            String type = question.getString("type");
            String description = question.getString("description");


            if (type.compareTo("radio") == 0 || type.compareTo("checkbox") == 0) {
                question.getInt("multiSelect");
                JSONArray optionsArray = question.getJSONArray("options");
                ChoiceQuestion choiceQuestion = JSON.parseObject(question.toString(), ChoiceQuestion.class);

                //插入选择题
                choiceQuestion.setQuestionnaireId(questionnaire.getId());
                choiceQuestion.setSerialNum(i + 1);
//                System.out.println(choiceQuestion);
                choiceQuestionService.addQuestion(choiceQuestion);
                Integer id = choiceQuestion.getId();
//                System.out.println(id);
                for (int j = 0; j < optionsArray.size(); j++) {
//                    System.out.println(optionsArray.get(j));
                    choice.setQuestionId(id);
                    choice.setDescription(optionsArray.get(j).toString());
//                    char ch = (char) ('A' + j);
//                    choice.setSerial(ch);
                    choiceService.addChoice(choice);
                }

            } else {
                //插入非选择题
                EssayQuestion essayQuestion = JSON.parseObject(question.toString(), EssayQuestion.class);
                essayQuestion.setQuestionnaireId(questionnaire.getId());
                essayQuestion.setDescription(description);
                essayQuestion.setSerialNum(i + 1);
//                System.out.println(essayQuestion);
                essayQuestionService.addQuestion(essayQuestion);
            }
        }

        return "SUCCESS";
    }


    @RequestMapping("saveResult")
    public String saveResult(String sendAnswersArray, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        String decode = URLDecoder.decode(sendAnswersArray, "utf-8");
        //System.out.println(decode);
        JSONObject jsonObject = JSONObject.fromObject(decode);
        JSONArray questionsArray = jsonObject.getJSONArray("answerArray");
        for (int i = 0; i < questionsArray.size(); i++) {
            Result result = JSON.parseObject(questionsArray.get(i).toString(), Result.class);
            String str = result.getResultChoice();
            if(str != null){
                StringBuilder stb = new StringBuilder(str);
/*                for(int j=0 ;j<str.length(); j++){
                    if(Character.isDigit(str.charAt(j))){
                        stb.setCharAt(j, (char)((int)str.charAt(j) + 17));
                    }
                }*/
                result.setResultChoice(stb.toString());
//                System.out.println(stb.toString());
            }
            resultService.addResult(result);
        }
        return null;
    }

    @RequestMapping("downLoad")
    public String downLoad(String questionnaireId, HttpServletResponse response) throws IOException {
        File file = new File("");
        String filePath = file.getCanonicalPath();
        //System.out.println(filePath);
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("结果统计表");

//        System.out.println(questionnaireId);

        List<String> resultString = new ArrayList<>();
        List<String> resultChoice = new ArrayList<>();
        List<String> description = new ArrayList<>();
        List<Integer> serial = new ArrayList<>();

        List<Result> results = resultService.quesyList(Integer.parseInt(questionnaireId));

        for (Result result : results) {
            if(result.getResultChoice() == null){//非选择题
                resultString.add(result.getResultString());
                resultChoice.add(" ");
                description.add(essayQuestionService.selectEssayQuestion(result.getQuestionId()).getDescription());
                serial.add(essayQuestionService.selectEssayQuestion(result.getQuestionId()).getSerialNum());
            }else{                              //选择题
                resultString.add(" ");
                resultChoice.add(result.getResultChoice());
                description.add(choiceQuestionService.selectChoiceQuestion(result.getQuestionId()).getDescription());
                serial.add(choiceQuestionService.selectChoiceQuestion(result.getQuestionId()).getSerialNum());
            }

        }
//        System.out.println(resultString);
//        System.out.println(resultChoice);
//        System.out.println(description);
//        System.out.println(serial);

        Row row1 = sheet.createRow(0);
        Cell cell1 = row1.createCell(0);
        cell1.setCellValue("序号");

        Cell cell2 = row1.createCell(1);
        cell2.setCellValue("题目");

        Cell cell3 = row1.createCell(2);
        cell3.setCellValue("选择题答案");

        Cell cell4 = row1.createCell(3);
        cell4.setCellValue("非选择题答案");

        int n = serial.size();
        for(int i=0 ; i < n ; i++){
            row1 = sheet.createRow(i+1);
            cell1 = row1.createCell(0);
            cell1.setCellValue(serial.get(i));

            cell1 = row1.createCell(1);
            cell1.setCellValue(description.get(i));
            cell1 = row1.createCell(2);
            cell1.setCellValue(resultChoice.get(i));
            cell1 = row1.createCell(3);
            cell1.setCellValue(resultString.get(i));

        }
//        Row row21 = sheet.createRow(1);
//        Cell cell21 = row21.createCell(0);
//        cell21.setCellValue("666");
//        Cell cell22 = row21.createCell(1);
//        cell22.setCellValue("99.9");

        FileOutputStream fileOutputStream = new FileOutputStream(filePath + questionnaireId +"问卷统计表.xls");
        workbook.write(fileOutputStream);
        fileOutputStream.close();

        return "生成完毕";
    }

    @RequestMapping("finishCountUp")
    public String finishCountUp(String id){
        questionnaireService.finishCountUp(Integer.parseInt(id));
        return "SUCCESS";
    }
}
